import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

// 用户信息仓库
export const useUserStore = defineStore('userInfo', () => {
  // 记录Assess Token
  const accessToken = ref(localStorage.getItem('accessToken') || '')

  //获取Access Token
  const getAccessToken = () => {
    return accessToken.value
  }

  //设置Access Token
  const setAccessToken = (newToken) => {
    accessToken.value = newToken
  }

  //移除token
  const removeAccessToken = () => {
    accessToken.value = ''
    localStorage.removeItem('accessToken')
  }

  //监听watch，如果token发生了变化则重置内存
  watch(accessToken, () => {
    localStorage.setItem('accessToken', accessToken.value)
  })

  //记录Refresh Token
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')

  //获取Refresh Token
  const getRefreshToken = () => {
    return refreshToken.value
  }

  //设置Refresh Token
  const setRefreshToken = (newToken) => {
    refreshToken.value = newToken
  }

  //移除Refresh Token
  const removeRefreshToken = () => {
    refreshToken.value = ''
    localStorage.removeItem('refreshToken')
  }

  //监听watch，如果token发生了变化则重置内存
  watch(refreshToken, () => {
    localStorage.setItem('refreshToken', refreshToken.value)
  })

  //记录用户id
  const userInfo = ref(localStorage.getItem('userId') || '')

  //获取用户信息
  const getUser = () => {
    return userInfo.value
  }

  //设置用户信息
  const setUser = (id) => {
    userInfo.value = id
  }

  //移除用户信息
  const removeUser = () => {
    userInfo.value = ''
    localStorage.removeItem('userId')
  }

  // 监听watch，如果userInfo发生了变化则重置内存
  watch(userInfo, () => {
    localStorage.setItem('userId', userInfo.value)
  })

  return {
    accessToken,
    getAccessToken,
    setAccessToken,
    removeAccessToken,
    refreshToken,
    getRefreshToken,
    setRefreshToken,
    removeRefreshToken,
    userInfo,
    getUser,
    setUser,
    removeUser,
  }
})
